// 增强图库管理脚本 - 支持轮播图、Logo、产品图、博客图统一管理
class EnhancedGalleryManager {
    constructor() {
        this.currentTab = 'gallery'; // gallery, carousel, logos, product-images, blog-images
        this.currentPage = 1;
        this.limit = 20;
        this.filters = {
            category: '',
            usageType: '',
            search: '',
            isActive: true
        };
        
        this.galleryData = [];
        this.carouselData = [];
        this.logosData = [];
        this.productImagesData = [];
        this.blogImagesData = [];
        
        this.stats = {
            gallery: { total: 0, active: 0 },
            carousel: { total: 0, active: 0 },
            logos: { total: 0, active: 0 },
            productImages: { total: 0, active: 0 },
            blogImages: { total: 0, active: 0 }
        };
    }

    // 初始化增强图库管理器
    async init() {
        await this.loadStats();
        this.setupEventListeners();
        this.setupTabNavigation();
        await this.loadCurrentTabData();
        this.renderStats();
    }

    // 加载统计数据
    async loadStats() {
        try {
            // 加载图库统计
            const galleryResponse = await apiClient.get('/gallery/stats/usage');
            if (galleryResponse.success) {
                this.stats.gallery.total = galleryResponse.data.reduce((sum, item) => sum + item.count, 0);
                this.stats.gallery.active = galleryResponse.data.reduce((sum, item) => sum + item.active_count, 0);
            }

            // 加载轮播图统计
            const carouselResponse = await apiClient.get('/carousel/stats');
            if (carouselResponse.success) {
                this.stats.carousel.total = carouselResponse.data.reduce((sum, item) => sum + item.count, 0);
                this.stats.carousel.active = carouselResponse.data.reduce((sum, item) => 
                    item.status ? sum + item.count : sum, 0);
            }

            // 加载Logo统计
            const logosResponse = await apiClient.get('/logos/stats');
            if (logosResponse.success) {
                this.stats.logos.total = logosResponse.data.reduce((sum, item) => sum + item.count, 0);
                this.stats.logos.active = logosResponse.data.reduce((sum, item) => sum + item.active_count, 0);
            }

            // 加载产品图统计
            const productImagesResponse = await apiClient.get('/product-images/stats');
            if (productImagesResponse.success) {
                this.stats.productImages.total = productImagesResponse.data.reduce((sum, item) => sum + item.imageCount, 0);
                this.stats.productImages.active = productImagesResponse.data.reduce((sum, item) => sum + item.activeCount, 0);
            }

            // 加载博客图统计
            const blogImagesResponse = await apiClient.get('/blog-images/stats');
            if (blogImagesResponse.success) {
                this.stats.blogImages.total = blogImagesResponse.data.reduce((sum, item) => sum + item.imageCount, 0);
                this.stats.blogImages.active = blogImagesResponse.data.reduce((sum, item) => sum + item.activeCount, 0);
            }

        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    // 设置事件监听器
    setupEventListeners() {
        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('input', this.debounce(() => {
                this.filters.search = searchInput.value;
                this.loadCurrentTabData();
            }, 300));
        }

        // 筛选器
        const categoryFilter = document.getElementById('categoryFilter');
        const usageTypeFilter = document.getElementById('usageTypeFilter');
        const statusFilter = document.getElementById('statusFilter');

        if (categoryFilter) {
            categoryFilter.addEventListener('change', () => {
                this.filters.category = categoryFilter.value;
                this.loadCurrentTabData();
            });
        }

        if (usageTypeFilter) {
            usageTypeFilter.addEventListener('change', () => {
                this.filters.usageType = usageTypeFilter.value;
                this.loadCurrentTabData();
            });
        }

        if (statusFilter) {
            statusFilter.addEventListener('change', () => {
                this.filters.isActive = statusFilter.value === 'active';
                this.loadCurrentTabData();
            });
        }

        // 上传按钮
        const uploadBtn = document.querySelector('.btn-primary');
        if (uploadBtn) {
            uploadBtn.addEventListener('click', () => {
                this.showUploadModal();
            });
        }
    }

    // 设置标签页导航
    setupTabNavigation() {
        const tabs = document.querySelectorAll('.gallery-tab');
        tabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                const tabName = tab.getAttribute('data-tab');
                this.switchTab(tabName);
            });
        });
    }

    // 切换标签页
    async switchTab(tabName) {
        this.currentTab = tabName;
        this.currentPage = 1;
        
        // 更新活跃标签样式
        document.querySelectorAll('.gallery-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        
        // 更新页面标题
        this.updatePageTitle(tabName);
        
        // 更新筛选器
        this.updateFiltersForTab(tabName);
        
        // 加载数据
        await this.loadCurrentTabData();
    }

    // 更新页面标题
    updatePageTitle(tabName) {
        const titles = {
            'gallery': '图库管理',
            'carousel': '轮播图管理',
            'logos': 'Logo管理',
            'product-images': '产品图片管理',
            'blog-images': '博客图片管理'
        };
        
        const titleElement = document.querySelector('.gallery-header h1');
        if (titleElement) {
            titleElement.innerHTML = `<i class="fas fa-images"></i> ${titles[tabName]}`;
        }
    }

    // 根据标签页更新筛选器
    updateFiltersForTab(tabName) {
        const filterContainer = document.querySelector('.gallery-filters');
        if (!filterContainer) return;

        // 重置筛选器
        this.filters = {
            category: '',
            usageType: '',
            search: '',
            isActive: true
        };

        // 根据标签页显示不同的筛选器
        switch (tabName) {
            case 'gallery':
                filterContainer.innerHTML = `
                    <div class="filter-group">
                        <select id="categoryFilter">
                            <option value="">所有分类</option>
                            <option value="product">产品图片</option>
                            <option value="banner">横幅图片</option>
                            <option value="logo">Logo图片</option>
                            <option value="background">背景图片</option>
                            <option value="other">其他图片</option>
                        </select>
                        
                        <select id="usageTypeFilter">
                            <option value="">所有用途</option>
                            <option value="carousel">轮播图</option>
                            <option value="featured">首页精选</option>
                            <option value="about">关于我们</option>
                            <option value="blog">博客创作</option>
                            <option value="product">产品管理</option>
                            <option value="general">通用图片</option>
                        </select>
                        
                        <select id="statusFilter">
                            <option value="">所有状态</option>
                            <option value="active">已启用</option>
                            <option value="inactive">已禁用</option>
                        </select>
                    </div>
                    
                    <div class="search-group">
                        <input type="text" id="searchInput" placeholder="搜索图片名称、描述或标签...">
                        <button class="btn-search">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                `;
                break;

            case 'carousel':
                filterContainer.innerHTML = `
                    <div class="filter-group">
                        <select id="statusFilter">
                            <option value="">所有状态</option>
                            <option value="active">已启用</option>
                            <option value="inactive">已禁用</option>
                        </select>
                    </div>
                    
                    <div class="search-group">
                        <input type="text" id="searchInput" placeholder="搜索轮播图名称或描述...">
                        <button class="btn-search">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                `;
                break;

            case 'logos':
                filterContainer.innerHTML = `
                    <div class="filter-group">
                        <select id="usageTypeFilter">
                            <option value="">所有用途</option>
                            <option value="main">主Logo</option>
                            <option value="footer">页脚Logo</option>
                            <option value="favicon">网站图标</option>
                            <option value="mobile">移动端Logo</option>
                            <option value="print">打印Logo</option>
                            <option value="social">社交媒体</option>
                            <option value="other">其他用途</option>
                        </select>
                        
                        <select id="statusFilter">
                            <option value="">所有状态</option>
                            <option value="active">已启用</option>
                            <option value="inactive">已禁用</option>
                        </select>
                    </div>
                    
                    <div class="search-group">
                        <input type="text" id="searchInput" placeholder="搜索Logo名称或描述...">
                        <button class="btn-search">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                `;
                break;

            case 'product-images':
                filterContainer.innerHTML = `
                    <div class="filter-group">
                        <input type="text" id="productIdFilter" placeholder="产品ID">
                        <select id="statusFilter">
                            <option value="">所有状态</option>
                            <option value="active">已启用</option>
                            <option value="inactive">已禁用</option>
                        </select>
                    </div>
                    
                    <div class="search-group">
                        <input type="text" id="searchInput" placeholder="搜索产品图片名称或描述...">
                        <button class="btn-search">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                `;
                break;

            case 'blog-images':
                filterContainer.innerHTML = `
                    <div class="filter-group">
                        <input type="text" id="blogIdFilter" placeholder="博客ID">
                        <select id="statusFilter">
                            <option value="">所有状态</option>
                            <option value="active">已启用</option>
                            <option value="inactive">已禁用</option>
                        </select>
                    </div>
                    
                    <div class="search-group">
                        <input type="text" id="searchInput" placeholder="搜索博客图片名称或描述...">
                        <button class="btn-search">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                `;
                break;
        }

        // 重新设置事件监听器
        this.setupEventListeners();
    }

    // 加载当前标签页数据
    async loadCurrentTabData() {
        try {
            let apiUrl = '';
            let params = {
                page: this.currentPage,
                limit: this.limit
            };

            // 根据当前标签页设置API和参数
            switch (this.currentTab) {
                case 'gallery':
                    apiUrl = '/gallery';
                    if (this.filters.category) params.category = this.filters.category;
                    if (this.filters.usageType) params.usageType = this.filters.usageType;
                    if (this.filters.search) params.search = this.filters.search;
                    if (this.filters.isActive !== undefined) params.isActive = this.filters.isActive;
                    break;

                case 'carousel':
                    apiUrl = '/carousel';
                    if (this.filters.isActive !== undefined) params.isActive = this.filters.isActive;
                    if (this.filters.search) params.search = this.filters.search;
                    break;

                case 'logos':
                    apiUrl = '/logos';
                    if (this.filters.usageType) params.usageType = this.filters.usageType;
                    if (this.filters.isActive !== undefined) params.isActive = this.filters.isActive;
                    if (this.filters.search) params.search = this.filters.search;
                    break;

                case 'product-images':
                    apiUrl = '/product-images';
                    if (this.filters.productId) params.productId = this.filters.productId;
                    if (this.filters.isActive !== undefined) params.isActive = this.filters.isActive;
                    if (this.filters.search) params.search = this.filters.search;
                    break;

                case 'blog-images':
                    apiUrl = '/blog-images';
                    if (this.filters.blogId) params.blogId = this.filters.blogId;
                    if (this.filters.isActive !== undefined) params.isActive = this.filters.isActive;
                    if (this.filters.search) params.search = this.filters.search;
                    break;
            }

            const response = await apiClient.get(apiUrl, params);
            if (response.success) {
                this[`${this.currentTab}Data`] = response.data;
                this.renderGrid();
                this.renderPagination(response.pagination);
            } else {
                throw new Error(response.message);
            }

        } catch (error) {
            console.error(`加载${this.currentTab}数据失败:`, error);
            this.showError(`加载数据失败: ${error.message}`);
        }
    }

    // 渲染图片网格
    renderGrid() {
        const gridContainer = document.getElementById('galleryGrid');
        if (!gridContainer) return;

        const data = this[`${this.currentTab}Data`];
        
        if (!data || data.length === 0) {
            gridContainer.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-images"></i>
                    <p>暂无图片数据</p>
                    <button class="btn-primary" onclick="enhancedGallery.showUploadModal()">
                        上传图片
                    </button>
                </div>
            `;
            return;
        }

        gridContainer.innerHTML = data.map(item => this.renderImageCard(item)).join('');
    }

    // 渲染单个图片卡片
    renderImageCard(item) {
        const isActive = item.isActive !== false;
        const statusText = isActive ? '已启用' : '已禁用';
        const statusClass = isActive ? 'status-active' : 'status-inactive';

        return `
            <div class="image-card" data-id="${item._id || item.id}">
                <div class="image-preview">
                    <img src="${item.imageUrl || item.image_url}" alt="${item.name}" 
                         onerror="this.src='/static/images/placeholder.jpg'">
                    <div class="image-overlay">
                        <button class="btn-icon" onclick="enhancedGallery.editImage('${item._id || item.id}')" 
                                title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn-icon" onclick="enhancedGallery.previewImage('${item._id || item.id}')" 
                                title="预览">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn-icon ${isActive ? 'btn-danger' : 'btn-success'}" 
                                onclick="enhancedGallery.toggleImageStatus('${item._id || item.id}', ${!isActive})" 
                                title="${isActive ? '禁用' : '启用'}">
                            <i class="fas ${isActive ? 'fa-ban' : 'fa-check'}"></i>
                        </button>
                    </div>
                </div>
                <div class="image-info">
                    <h4>${item.name}</h4>
                    <p class="image-description">${item.description || '暂无描述'}</p>
                    <div class="image-meta">
                        <span class="status ${statusClass}">${statusText}</span>
                        <span class="file-size">${this.formatFileSize(item.fileSize)}</span>
                    </div>
                    ${this.renderAdditionalInfo(item)}
                </div>
            </div>
        `;
    }

    // 渲染附加信息（根据图片类型）
    renderAdditionalInfo(item) {
        switch (this.currentTab) {
            case 'carousel':
                return `<div class="image-type">轮播图</div>`;
            
            case 'logos':
                const usageTypes = {
                    'main': '主Logo',
                    'footer': '页脚Logo',
                    'favicon': '网站图标',
                    'mobile': '移动端Logo',
                    'print': '打印Logo',
                    'social': '社交媒体',
                    'other': '其他用途'
                };
                return `<div class="image-type">${usageTypes[item.usageType] || item.usageType}</div>`;
            
            case 'product-images':
                return `
                    <div class="image-type">
                        ${item.isMain ? '主图' : '产品图'}
                        ${item.productId ? `<br><small>产品ID: ${item.productId}</small>` : ''}
                    </div>
                `;
            
            case 'blog-images':
                return `
                    <div class="image-type">
                        ${item.isCover ? '封面图' : '博客图'}
                        ${item.blogId ? `<br><small>博客ID: ${item.blogId}</small>` : ''}
                    </div>
                `;
            
            default:
                return `
                    <div class="image-type">
                        ${item.category || '未分类'}
                        ${item.usageType ? `<br><small>用途: ${item.usageType}</small>` : ''}
                    </div>
                `;
        }
    }

    // 渲染分页
    renderPagination(pagination) {
        const paginationContainer = document.getElementById('pagination');
        if (!paginationContainer || !pagination) return;

        const { page, totalPages } = pagination;
        
        if (totalPages <= 1) {
            paginationContainer.innerHTML = '';
            return;
        }

        let paginationHTML = '<div class="pagination-controls">';
        
        // 上一页
        if (page > 1) {
            paginationHTML += `<button class="btn-pagination" onclick="enhancedGallery.goToPage(${page - 1})">
                <i class="fas fa-chevron-left"></i> 上一页
            </button>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === page) {
                paginationHTML += `<span class="page-current">${i}</span>`;
            } else if (i === 1 || i === totalPages || (i >= page - 2 && i <= page + 2)) {
                paginationHTML += `<button class="btn-pagination" onclick="enhancedGallery.goToPage(${i})">${i}</button>`;
            } else if (i === page - 3 || i === page + 3) {
                paginationHTML += '<span class="page-ellipsis">...</span>';
            }
        }

        // 下一页
        if (page < totalPages) {
            paginationHTML += `<button class="btn-pagination" onclick="enhancedGallery.goToPage(${page + 1})">
                下一页 <i class="fas fa-chevron-right"></i>
            </button>`;
        }

        paginationHTML += '</div>';
        paginationContainer.innerHTML = paginationHTML;
    }

    // 渲染统计信息
    renderStats() {
        const statsContainer = document.querySelector('.gallery-stats');
        if (!statsContainer) return;

        statsContainer.innerHTML = `
            <div class="stats-grid">
                <div class="stat-item" data-tab="gallery">
                    <div class="stat-value">${this.stats.gallery.total}</div>
                    <div class="stat-label">总图片数</div>
                    <div class="stat-active">${this.stats.gallery.active} 启用</div>
                </div>
                <div class="stat-item" data-tab="carousel">
                    <div class="stat-value">${this.stats.carousel.total}</div>
                    <div class="stat-label">轮播图</div>
                    <div class="stat-active">${this.stats.carousel.active} 启用</div>
                </div>
                <div class="stat-item" data-tab="logos">
                    <div class="stat-value">${this.stats.logos.total}</div>
                    <div class="stat-label">Logo</div>
                    <div class="stat-active">${this.stats.logos.active} 启用</div>
                </div>
                <div class="stat-item" data-tab="product-images">
                    <div class="stat-value">${this.stats.productImages.total}</div>
                    <div class="stat-label">产品图</div>
                    <div class="stat-active">${this.stats.productImages.active} 启用</div>
                </div>
                <div class="stat-item" data-tab="blog-images">
                    <div class="stat-value">${this.stats.blogImages.total}</div>
                    <div class="stat-label">博客图</div>
                    <div class="stat-active">${this.stats.blogImages.active} 启用</div>
                </div>
            </div>
        `;

        // 为统计项添加点击事件
        statsContainer.querySelectorAll('.stat-item').forEach(item => {
            item.addEventListener('click', () => {
                const tab = item.getAttribute('data-tab');
                this.switchTab(tab);
            });
        });
    }

    // 显示上传模态框
    showUploadModal() {
        // 根据当前标签页显示不同的上传表单
        const modalContent = this.getUploadModalContent();
        
        // 这里需要实现模态框显示逻辑
        console.log('显示上传模态框:', this.currentTab);
        // 实际项目中应该使用现有的模态框系统
    }

    // 获取上传模态框内容
    getUploadModalContent() {
        const templates = {
            'gallery': '通用图片上传表单',
            'carousel': '轮播图上传表单',
            'logos': 'Logo上传表单',
            'product-images': '产品图片上传表单',
            'blog-images': '博客图片上传表单'
        };
        
        return templates[this.currentTab] || '通用上传表单';
    }

    // 编辑图片
    async editImage(imageId) {
        try {
            let apiUrl = '';
            switch (this.currentTab) {
                case 'gallery': apiUrl = `/gallery/${imageId}`; break;
                case 'carousel': apiUrl = `/carousel/${imageId}`; break;
                case 'logos': apiUrl = `/logos/${imageId}`; break;
                case 'product-images': apiUrl = `/product-images/${imageId}`; break;
                case 'blog-images': apiUrl = `/blog-images/${imageId}`; break;
            }

            const response = await apiClient.get(apiUrl);
            if (response.success) {
                this.showEditModal(response.data);
            }
        } catch (error) {
            console.error('获取图片详情失败:', error);
            this.showError('获取图片详情失败');
        }
    }

    // 预览图片
    previewImage(imageId) {
        const data = this[`${this.currentTab}Data`].find(item => (item._id || item.id) === imageId);
        if (data) {
            this.showPreviewModal(data);
        }
    }

    // 切换图片状态
    async toggleImageStatus(imageId, newStatus) {
        try {
            let apiUrl = '';
            switch (this.currentTab) {
                case 'gallery': apiUrl = `/gallery/${imageId}`; break;
                case 'carousel': apiUrl = `/carousel/${imageId}/toggle`; break;
                case 'logos': apiUrl = `/logos/${imageId}`; break;
                case 'product-images': apiUrl = `/product-images/${imageId}`; break;
                case 'blog-images': apiUrl = `/blog-images/${imageId}`; break;
            }

            const response = await apiClient.put(apiUrl, { isActive: newStatus });
            if (response.success) {
                this.showSuccess(`图片已${newStatus ? '启用' : '禁用'}`);
                await this.loadCurrentTabData();
                await this.loadStats();
                this.renderStats();
            }
        } catch (error) {
            console.error('切换图片状态失败:', error);
            this.showError('切换状态失败');
        }
    }

    // 跳转到指定页面
    goToPage(page) {
        this.currentPage = page;
        this.loadCurrentTabData();
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (!bytes) return '0 B';
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(1024));
        return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }

    // 显示成功消息
    showSuccess(message) {
        // 使用现有的消息系统
        if (typeof showNotification === 'function') {
            showNotification(message, 'success');
        } else {
            alert('成功: ' + message);
        }
    }

    // 显示错误消息
    showError(message) {
        // 使用现有的消息系统
        if (typeof showNotification === 'function') {
            showNotification(message, 'error');
        } else {
            alert('错误: ' + message);
        }
    }

    // 显示编辑模态框（需要实现）
    showEditModal(data) {
        console.log('显示编辑模态框:', data);
        // 实际项目中应该实现具体的编辑表单
    }

    // 显示预览模态框（需要实现）
    showPreviewModal(data) {
        console.log('显示预览模态框:', data);
        // 实际项目中应该实现图片预览功能
    }
}

// 创建全局实例
const enhancedGallery = new EnhancedGalleryManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    enhancedGallery.init();
});